package com.fc.authentication.common.utils;

import com.google.gson.Gson;
import com.google.gson.JsonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;

/**
 * Created by futurecreative on 2017/7/14.
 */
public class JsonUtils {
    private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);

    private static final String ENCODING = "UTF-8";
    private static final String CONTENT_TYPE = "application/json";

    private static Gson gson=new Gson();
    private JsonUtils() {
    }
    /**
     * @MethodName : toJson
     * @Description : 将对象转为JSON串，此方法能够满足大部分需求
     * @param src
     *            :将要被转化的对象
     * @return :转化后的JSON串
     */
    public static String toJson(Object src) {
        if (src == null) {
            return gson.toJson(JsonNull.INSTANCE);
        }
        return gson.toJson(src);
    }

    /**
     * @MethodName : fromJson
     * @Description : 用来将JSON串转为对象，但此方法不可用来转带泛型的集合
     * @param json
     * @param classOfT
     * @return
     */
    public static <T> T fromJson(String json, Class<T> classOfT) {
        return gson.fromJson(json, (Type) classOfT);
    }

    /**
     * @MethodName : fromJson
     * @Description : 用来将JSON串转为对象，此方法可用来转带泛型的集合，如：Type为
     *              new TypeToken<List<T>>(){}.getType()
     *              ，其它类也可以用此方法调用，就是将List<T>替换为你想要转成的类
     * @param json
     * @param typeOfT
     * @return
     */
    public static Object fromJson(String json, Type typeOfT) {
        return gson.fromJson(json, typeOfT);
    }

    public static void out(HttpServletResponse response, Object obj) {
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding(ENCODING);
        PrintWriter outResponse = null;

        try {
            outResponse = response.getWriter();
            outResponse.print(toJson(obj));
            outResponse.flush();
        } catch (IOException e) {
            log.error("json utils exception :" + e);
        } finally {
            if (outResponse != null) {
                outResponse.close();
            }
        }
    }
}
